<template>
  <div class="image-preview">
    <el-image
      v-for="(item,index) in fileList"
      :key="index"
      :src="item.url"
      fit="cover"
      :style="`width:${realWidth};height:${realHeight};`"
      :preview-src-list="realSrcList"
    >
      <div slot="error" class="image-slot">
        <i class="el-icon-picture-outline"></i>
      </div>
    </el-image>
    <div v-if="fileList.length==0">未上传</div>
  </div>
</template>

<script>
export default {
  name: "ImagePreview",
  props: {
    url: {
      required: true
    },
    width: {
      type: [Number, String],
      default: "78px"
    },
    height: {
      type: [Number, String],
      default: "78px"
    }
  },
  data() {
    return {
      fileList: []
    };
  },
  watch: {
    url: {
      handler(val) {
        if (val) {
          this.fileList = Array.isArray(val) ? val : (val.indexOf('[{')==0?JSON.parse(val):val.split(',').map(row=>({url:row,name:row.split('/').pop()})));
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    realSrcList() {
      return this.fileList.map(row=>row.url);
    },
    realWidth() {
      return typeof this.width == "string" ? this.width : `${this.width}px`;
    },
    realHeight() {
      return typeof this.height == "string" ? this.height : `${this.height}px`;
    }
  },
};
</script>

<style lang="scss" scoped>
.image-preview{
  .el-image {
    border-radius: 5px;
    margin: 4px;
    vertical-align: bottom;
    border: 1px dashed #ebeef5;
    ::v-deep .el-image__inner {
      transition: all 0.3s;
      cursor: pointer;
      &:hover {
        transform: scale(1.2);
      }
    }
    ::v-deep .image-slot {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      color: #909399;
      font-size: 30px;
    }
  }
}
</style>
